#include <jni.h>
#include <string>

#include <android/log.h>

#define LOG_TAG "clog"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)


extern "C" {

char *Jstring2CStr(JNIEnv *env, jstring jstr) {
    char *rtn = NULL;
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("UTF-8");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid,
                                                         strencode); // String .getByte("GB2312");
    jsize alen = env->GetArrayLength(barr);
    jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0) {
        rtn = (char *) malloc(alen + 1);         //"\0"
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);  //
    return rtn;
}

JNIEXPORT jstring JNICALL Java_com_jacky_me_jnidemo_calljni_LoadCMethod_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

/*
 * Class:     com_jacky_me_jnidemo_calljni_LoadCMethod
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL
Java_com_jacky_me_jnidemo_calljni_LoadCMethod_add(JNIEnv *env, jobject, jint x, jint y) {
    // 想在logcat控制台上 打印日志
    // log.i(TAG,"sss");
    LOGD("x=%d", x);
    LOGI("y=%d", y);
    return x + y;
}

/*
 * Class:     com_jacky_me_jnidemo_calljni_LoadCMethod
 * Method:    sayHelloInC
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_jacky_me_jnidemo_calljni_LoadCMethod_jointHelloToJstring
        (JNIEnv *env, jobject, jstring str) {
    char *c = "hello";
    // 在C语言中不能直接操作java中的字符串
    // 把java中的字符串转换成c语言中 char数组
    char *cstr = Jstring2CStr(env, str);

    strcat(cstr, c);
//    LOGD("%s", cstr);
    return env->NewStringUTF(cstr);
}

/*
 * Class:     com_jacky_me_jnidemo_calljni_LoadCMethod
 * Method:    intMethod
 * Signature: ([I)[I
 */
JNIEXPORT jintArray JNICALL Java_com_jacky_me_jnidemo_calljni_LoadCMethod_modifyIntArrayValue
        (JNIEnv *env, jobject, jintArray jarray) {
    // jArray  遍历数组   jint*       (*GetIntArrayElements)(JNIEnv*, jintArray, jboolean*);
    // 数组的长度    jsize       (*GetArrayLength)(JNIEnv*, jarray);
    // 对数组中每个元素 +5
    int length = env->GetArrayLength(jarray);// jsize length = env->GetArrayLength(jarray);
    jint *arrayPointer = env->GetIntArrayElements(jarray, 0);
    int i = 0;
    for (; i < length; i++) {
        *(arrayPointer + i) += 5;
    }
    env->SetIntArrayRegion(jarray, 0, length, arrayPointer);
    return jarray;
}


}














